package com.cn.studySpring.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.context.request.NativeWebRequest;

import com.cn.studySpring.exception.NotFoundException;

/** 
 * 通用的exception的handler的定义 
 * 使一个Contoller成为全局的异常处理类，类中用@ExceptionHandler方法注解的方法可以处理所有Controller发生的异常
 * @author jshi 
 * @date 2016-6-5 
 */  
@ControllerAdvice  
public class ExceptionAdvice {
	
	//全局性异常处理
	@ExceptionHandler({ Exception.class })
	@ResponseBody
	public String handException(HttpServletRequest request ,Exception e) throws Exception {
	e.printStackTrace();
	//If the exception is annotated with @ResponseStatus rethrow it and let
	// the framework handle it - like the OrderNotFoundException example
	// at the start of this post.
	// AnnotationUtils is a Spring Framework utility class.
	if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null){
	throw e;
	}
	// Otherwise setup and send the user to a default error-view.
	/*ModelAndView mav = new ModelAndView();
	mav.addObject("exception", e);
	mav.addObject("url", request.getRequestURL());
	mav.setViewName(DEFAULT_ERROR_VIEW);
	return mav;*/
	System.out.println("===========应用到所有@RequestMapping注解的方法，在其抛出全局异常时执行");  
     
	return e.getMessage();
	}
	
	
   /* @ModelAttribute  
    public void toSuer() {  
        System.out.println("============应用到所有@RequestMapping注解方法，在其执行之前把返回值放入Model");
    }  
  
    @InitBinder  
    public void initBinder(WebDataBinder binder) {  
        System.out.println("============应用到所有@RequestMapping注解方法，在其执行之前初始化数据绑定器");  
    }  */
  
    @ExceptionHandler(NotFoundException.class)  
    @ResponseStatus(HttpStatus.UNAUTHORIZED)  
    public String processUnauthenticatedException(NativeWebRequest request, NotFoundException e) {  
        System.out.println("===========应用到所有@RequestMapping注解的方法，在其抛出UnauthenticatedException异常时执行");  
        return "viewName"; //返回一个逻辑视图名  
    }


}  